package security.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;


/**
   *
   * 功能描述:   用户实体类
   *
   * @param:
   * @return:
   * @auther: YiTong
   * @date: 2019/2/10 23:30
   */
@Getter
@Setter
@Entity
@ToString
public class SysUser implements UserDetails {
      /**
       * 主键
       */
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
      /**
       * 用户名
       * 唯一约束
       */
    @Column(unique = true)
    private String username;
      /**
       * 密码
       */
    private String password;
      /**
       * 拥有的集合
       * 用set集合接收角色防止重复
       * cascade 操作
       * orphanRemoval 级联删除
       */
    @TableField(exist = false)
    @OneToMany(fetch = FetchType.EAGER,cascade={CascadeType.ALL},orphanRemoval=true)
    private Set<Role> roles;
    /**
     * 用户状态
     */
    private Integer status;

    public SysUser() {
    }

    public SysUser(String username, String password) {
        this.username = username;
        this.password = password;
    }


    /**
       * 角色集合
       * @return
       */
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> auths = new HashSet<>();
        Set<Role> roles = this.getRoles();
        for (Role role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getName()));
        }
        return auths;
    }

    /**
     * 帐户是否未过期
     * @return
     */
    private  boolean isAccountNonExpired=true;
    @Override
    public boolean isAccountNonExpired() {
        return this.isAccountNonExpired;
    }

    /**
     * 账号是否被锁
     * @return
     */
    private  boolean isAccountNonLocked=true;
    @Override
    public boolean isAccountNonLocked() {
        return this.isAccountNonLocked;
    }

    /**
     * 凭据是否未过期
     * @return
     */
    private  boolean isCredentialsNonExpired=true;
    @Override
    public boolean isCredentialsNonExpired() {
        return this.isCredentialsNonExpired;
    }

    /**
     * 是否启用
     * @return
     */
    private  boolean isEnabled=true;
    @Override
    public boolean isEnabled() {
        return this.isEnabled;
    }
}
